// 蜂窝蜜造平台生成代码，如手工更改，请添加到 .beeignore 忽略生成

package com.fowo.api.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.common.annotaion.DataObjectType;
import com.fowo.api.common.config.CacheConfig;
import com.fowo.api.common.excel.CustomExcelExport;
import com.fowo.api.common.excel.CustomExcelHandler;
import com.fowo.api.common.excel.ExcelConfig;
import com.fowo.api.common.excel.TemplateModelBuildEventListener;
import com.fowo.api.common.model.DataIndex;
import com.fowo.api.common.model.ImportRow;
import com.fowo.api.common.model.JoinModel;
import com.fowo.api.common.model.OptionItem;
import com.fowo.api.common.model.PageSearchFilter;
import com.fowo.api.common.model.RException;
import com.fowo.api.common.util.ContextHolder;
import com.fowo.api.common.util.DateUtils;
import com.fowo.api.common.util.ResponseUtils;
import com.fowo.api.common.util.SheetUtils;
import com.fowo.api.entity.Receipt;
import com.fowo.api.flow.entity.WorkFlow;
import com.fowo.api.flow.service.WorkFlowService;
import com.fowo.api.mapper.LogisticsProviderMapper;
import com.fowo.api.mapper.PurchaseOrderMapper;
import com.fowo.api.mapper.ReceiptMapper;
import com.fowo.api.mapper.ReceiptProductMapper;
import com.fowo.api.mapper.SupplierMapper;
import com.fowo.api.mapper.WarehouseMapper;
import com.fowo.api.model.logistics.provider.LogisticsProviderItemVo;
import com.fowo.api.model.logistics.provider.LogisticsProviderSearchParamPo;
import com.fowo.api.model.purchase.order.PurchaseOrderItemVo;
import com.fowo.api.model.purchase.order.PurchaseOrderSearchParamPo;
import com.fowo.api.model.receipt.ReceiptExcelPo;
import com.fowo.api.model.receipt.ReceiptImportAndReceiveAction;
import com.fowo.api.model.receipt.ReceiptImportPo;
import com.fowo.api.model.receipt.ReceiptImportShortcutToLibraryAction;
import com.fowo.api.model.receipt.ReceiptItemVo;
import com.fowo.api.model.receipt.ReceiptPrintProductBarCodesCustomAction;
import com.fowo.api.model.receipt.ReceiptPrintProductBarCodesTemplateAction;
import com.fowo.api.model.receipt.ReceiptQuerySubtableParam;
import com.fowo.api.model.receipt.ReceiptQuerySubtableResult;
import com.fowo.api.model.receipt.ReceiptSearchParamPo;
import com.fowo.api.model.receipt.ReceiptVo;
import com.fowo.api.model.receipt.constant.ReceiptCostDistributionEnums;
import com.fowo.api.model.receipt.constant.ReceiptReceiptTypeEnums;
import com.fowo.api.model.receipt.constant.ReceiptStatusEnums;
import com.fowo.api.model.receipt.product.ReceiptProductItemVo;
import com.fowo.api.model.receipt.product.ReceiptProductItemVoPages;
import com.fowo.api.model.receipt.product.ReceiptProductSearchParamPo;
import com.fowo.api.model.supplier.SupplierItemVo;
import com.fowo.api.model.supplier.SupplierSearchParamPo;
import com.fowo.api.model.warehouse.WarehouseItemVo;
import com.fowo.api.model.warehouse.WarehouseSearchParamPo;
import com.fowo.api.service.ReceiptProductService;
import com.fowo.api.service.ReceiptService;
import com.fowo.api.sys.annotation.DataActivity;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import com.fowo.api.sys.component.SysDataActivityAopHelper;
import com.fowo.api.sys.entity.SysFile;
import com.fowo.api.sys.entity.SysImportTemplate;
import com.fowo.api.sys.entity.enums.SysDataActivityAction;
import com.fowo.api.sys.mapper.SysUserMapper;
import com.fowo.api.sys.model.NewSerialRequest;
import com.fowo.api.sys.model.SysDictAllItem;
import com.fowo.api.sys.model.SysUserItemVo;
import com.fowo.api.sys.model.SysUserSearch;
import com.fowo.api.sys.service.FileService;
import com.fowo.api.sys.service.SysDictService;
import com.fowo.api.sys.service.SysImportTemplateService;
import com.fowo.api.sys.service.SysSerialService;
import com.fowo.api.user.model.JwtUserInfo;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

/**
 * 收货单 服务实现类
 * @author 蜂窝蜜造平台 配置人：鹿丙涛
 */
@Service
@Slf4j
@DataObjectType(Receipt.class)
@DS("ds24")
public class ReceiptServiceImpl
  extends ServiceImpl<ReceiptMapper, Receipt>
  implements ReceiptService {

  /** 引用字段排序字段名转换信息 */
  public static final Map<String, String> SORT_FIELD_MAP = new HashMap<>() {
    {
      put("docRelatePurchaseOrderCode", "po.`purchase_order_code`");
      put("warehouseName", "w.`name`");
      put("supplierSupplierName", "s.`supplier_name`");
      put("shipmentEnterpriseName", "lp.`name`");
      put("buyerName", "su.`name`");
      put("creatorName", "su2.`name`");
      put("createUserName", "su3.`name`");
      put("consigneeName", "su4.`name`");
      put("clerkName", "w2.`name`");
    }
  };
  // 导出时单次查询最大记录数
  protected static final int EXPORT_QUERY_MAX_SIZE = 1000;
  // 支持导出的最大记录数(1048576 为 Excel 支持的最大行数)
  protected static final long EXPORT_MAX_SIZE = 1048575;

  /**
   * 服务自引用，用于调用服务方法时包括 AOP 处理
   */
  @Resource
  protected ReceiptService self;

  @Resource
  protected ReceiptProductService receiptProductService;

  @Resource
  protected SysSerialService sysSerialService;

  @Resource
  private SysDictService sysDictService;

  @Resource
  protected PurchaseOrderMapper purchaseOrderMapper;

  @Resource
  protected WarehouseMapper warehouseMapper;

  @Resource
  protected SupplierMapper supplierMapper;

  @Resource
  protected LogisticsProviderMapper logisticsProviderMapper;

  @Resource
  protected SysUserMapper sysUserMapper;

  @Resource
  protected FileService fileService;

  @Resource
  protected SysImportTemplateService importTemplateService;

  @Resource
  private CustomExcelExport customExcelExport;

  @Resource
  protected WorkFlowService workFlowService;

  @Autowired(required = false)
  protected ReceiptPrintProductBarCodesCustomAction receiptPrintProductBarCodesCustomAction;

  @Autowired(required = false)
  protected ReceiptPrintProductBarCodesTemplateAction receiptPrintProductBarCodesTemplateAction;

  @Autowired(required = false)
  protected ReceiptImportAndReceiveAction receiptImportAndReceiveAction;

  @Autowired(required = false)
  protected ReceiptImportShortcutToLibraryAction receiptImportShortcutToLibraryAction;

  @Resource
  private ExecuteScriptEngine executeScriptEngine;

  @Resource
  protected Validator validator;

  /**
   * 创建收货单
   * @param model 收货单
   * @return 新数据的主键
   */
  @DataActivity(action = SysDataActivityAction.Add)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public Long create(ReceiptVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Receipt entity = new Receipt();
    BeanUtils.copyProperties(model, entity);
    entity.setCreateTime(new Date());
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setCreateUser(currentUser.getUserId());
      entity.setLastUpdateUser(currentUser.getUserId());
    }

    if (model.getReceiptType() == null) {
      entity.setReceiptType("1");
    }

    if (model.getStatus() == null) {
      entity.setStatus("0");
    }

    if (model.getCostDistribution() == null) {
      entity.setCostDistribution("0");
    }

    if (model.getUrgent() == null) {
      entity.setUrgent("0");
    }
    // 填充序列号
    if (!StringUtils.hasText(entity.getOrderSn())) {
      entity.setOrderSn(
        sysSerialService.getNewSerial(
          new NewSerialRequest(null, "Receipt.orderSn")
        )
      );
    }
    // 源表检测字段 默认值设置
    if (!StringUtils.hasText(model.getDetectionFlag())) {
      model.setDetectionFlag("1");
    }
    if (this.save(entity)) {
      model.setId(entity.getId());
      updateAllChilds(model);
      return entity.getId();
    }
    throw new Exception("收货单保存失败");
  }

  /**
   * 更新所有子表
   * @param model 收货单
   */
  protected void updateAllChilds(ReceiptVo model) throws Exception {
    if (model.getReceiptList() != null) {
      receiptProductService.saveAllByParentReceipt(
        model.getId(),
        model.getReceiptList()
      );
    }
  }

  /**
   * 更新收货单
   * @param model 收货单
   * @return 更新是否成功
   */
  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean update(ReceiptVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Receipt entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("收货单不存在");
    }
    BeanUtils.copyProperties(
      model,
      entity,
      "id",
      "buyer",
      "creator",
      "createUser",
      "createTime",
      "lastUpdateUser",
      "lastUpdateTime",
      "costDistribution",
      "detectionFlag"
    );
    entity.setLastUpdateTime(new Date());
    if (currentUser != null) {
      entity.setLastUpdateUser(currentUser.getUserId());
    }
    if (this.updateById(entity)) {
      updateAllChilds(model);
      return true;
    }
    return false;
  }/**
   * 更新收货单（带空值）
   * @param model 收货单
   * @return 更新是否成功
   */

  @DataActivity(action = SysDataActivityAction.Modified)
  @Override
  @Transactional(rollbackFor = Exception.class)
  public boolean updateForEdit(ReceiptVo model) throws Exception {
    JwtUserInfo currentUser = JwtUserInfo.fromHeader();
    Receipt entity = this.getById(model.getId());
    if (entity == null) {
      throw new Exception("收货单不存在");
    }
    model.setLastUpdateTime(new Date());
    if (currentUser != null) {
      model.setLastUpdateUser(currentUser.getUserId());
    }
    boolean isOk = new LambdaUpdateChainWrapper<>(baseMapper)
      .set(Receipt::getReceiptType, model.getReceiptType())
      .set(Receipt::getDocRelate, model.getDocRelate())
      .set(Receipt::getWarehouse, model.getWarehouse())
      .set(Receipt::getSupplier, model.getSupplier())
      .set(Receipt::getArrivalGoodDate, model.getArrivalGoodDate())
      .set(Receipt::getShipmentEnterprise, model.getShipmentEnterprise())
      .set(Receipt::getLogisticsCode, model.getLogisticsCode())
      .set(Receipt::getLastUpdateUser, model.getLastUpdateUser())
      .set(Receipt::getLastUpdateTime, model.getLastUpdateTime())
      .set(Receipt::getConsignee, model.getConsignee())
      .set(Receipt::getReceiptDate, model.getReceiptDate())
      .set(Receipt::getRemarks, model.getRemarks())
      .set(Receipt::getFreight, model.getFreight())
      .set(Receipt::getOtherExpenses, model.getOtherExpenses())
      .set(
        model.getAppendix() != null,
        Receipt::getAppendix,
        JSON.toJSONString(model.getAppendix())
      )
      .setSql(model.getAppendix() == null, "appendix = null")
      .set(Receipt::getUrgent, model.getUrgent())
      .set(
        Receipt::getNotificationOfReceiptQuantity,
        model.getNotificationOfReceiptQuantity()
      )
      .set(Receipt::getReceiptAboutQuantity, model.getReceiptAboutQuantity())
      .set(
        model.getReceiptAboutProduct() != null,
        Receipt::getReceiptAboutProduct,
        JSON.toJSONString(model.getReceiptAboutProduct())
      )
      .setSql(
        model.getReceiptAboutProduct() == null,
        "receipt_about_product = null"
      )
      .eq(Receipt::getId, model.getId())
      .update();
    if (isOk) {
      updateAllChilds(model);
    }
    return isOk;
  }

  /**
   * 是否走导出中心
   */
  @Override
  public boolean getBackgroundExportFlag(ReceiptSearchParamPo search) {
    return false;
  }

  /**
   * 批量删除指定主键列表关联的所有子表数据(此方法不包括事务，必须由其它已包括事务的方法调用)
   */
  protected void batchDeleteChilds(List<Long> ids) throws Exception {
    // 处理子表字段 产品列表(receiptList) 对应的对象
    ReceiptProductSearchParamPo receiptListSearchParam =
      new ReceiptProductSearchParamPo();
    receiptListSearchParam.setDisableDataPremissions(true);
    receiptListSearchParam.setParentReceiptInList(ids);
    ReceiptProductMapper localReceiptProductMapper = ContextHolder
      .getApplicationContext()
      .getBean(ReceiptProductMapper.class);
    receiptListSearchParam.applySqlSegments();
    List<Long> receiptListIdList = localReceiptProductMapper.searchIds(
      receiptListSearchParam
    );
    if (!receiptListIdList.isEmpty()) {
      ReceiptProductService localReceiptProductService = ContextHolder
        .getApplicationContext()
        .getBean(ReceiptProductService.class);
      localReceiptProductService.batchDelete(receiptListIdList);
    }
  }

  /**
   * 删除收货单
   * @param id 收货单的主键
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean delete(Long id) throws Exception {
    batchDeleteChilds(Collections.singletonList(id));
    return this.removeById(id);
  }

  /**
   * 批量删除收货单
   * @param ids 收货单的主键列表
   * @return 删除是否成功
   */
  @DataActivity(action = SysDataActivityAction.Del)
  @Override
  public boolean batchDelete(List<Long> ids) throws Exception {
    batchDeleteChilds(ids);

    int count = 0;
    for (int i = 0; i < ids.size(); i += 2000) {
      count +=
        baseMapper.deleteBatchIds(
          ids.stream().skip(i).limit(2000).collect(Collectors.toList())
        );
    }
    return count > 0;
  }

  /**
   * 导入单行处理
   * @param row 要导入的行
   * @param rowNumber 所在行号
   * @param vo 输出VO,可空
   * @param variables 变量池，用于在一次导入过程中保存临时信息
   * @param allowOverrides 允许覆盖
   * @return 导入行对象
   */
  protected ImportRow<ReceiptImportPo> excelToImportRow(
    ReceiptImportPo row,
    Integer rowNumber,
    ReceiptVo vo,
    Map<String, Object> variables,
    boolean allowOverrides
  ) {
    ImportRow<ReceiptImportPo> ir = new ImportRow<ReceiptImportPo>();
    ir.setRowNumber(rowNumber);
    ir.setRow(row);
    if (SheetUtils.isAllFieldsEmpty(row)) {
      ir.setEmptyRow(true);
      ir.addError("", "空行");
      return ir;
    }
    final Set<ConstraintViolation<ReceiptImportPo>> validate =
      validator.validate(row);
    boolean isOutputVo = vo != null;
    if (!isOutputVo) {
      vo = new ReceiptVo();
    }
    BeanUtils.copyProperties(row, vo);
    // 收集基本校验错误
    ir.initErrors(validate, ReceiptImportPo.class);

    // 一般数据处理
    if (StringUtils.hasText(row.getReceiptType())) {
      vo.setReceiptType(ReceiptReceiptTypeEnums.toValue(row.getReceiptType()));
      if (vo.getReceiptType() == null) {
        ir.addError("receiptType", "收货类型只能是：“ 采购订单”, “ 委外订单”");
      }
    }
    vo.setArrivalGoodDate(SheetUtils.tryToDateTime(row.getArrivalGoodDate()));
    vo.setReceiptDate(SheetUtils.tryToDateTime(row.getReceiptDate()));
    if (StringUtils.hasText(row.getStatus())) {
      vo.setStatus(ReceiptStatusEnums.toValue(row.getStatus()));
      if (vo.getStatus() == null) {
        ir.addError("status", "单据状态只能是：“待收货”, “已完成”");
      }
    }
    if (StringUtils.hasText(row.getCostDistribution())) {
      vo.setCostDistribution(
        ReceiptCostDistributionEnums.toValue(row.getCostDistribution())
      );
      if (vo.getCostDistribution() == null) {
        ir.addError(
          "costDistribution",
          "费用分配方式只能是：“不分摊”, “按金额”, “按数量”"
        );
      }
    }
    vo.setFreight(SheetUtils.tryToDecimal(row.getFreight()));
    vo.setOtherExpenses(SheetUtils.tryToDecimal(row.getOtherExpenses()));
    vo.setAllTotalStorage(SheetUtils.tryToInteger(row.getAllTotalStorage()));
    if (StringUtils.hasText(row.getUrgent())) {
      List<SysDictAllItem> urgentItems =
        (List<SysDictAllItem>) variables.computeIfAbsent(
          "urgent",
          n -> sysDictService.getDictItems("SCM00008")
        );
      ReceiptVo finalVo = vo;
      urgentItems
        .stream()
        .filter(i -> i.getItemText().equals(row.getUrgent()))
        .findFirst()
        .ifPresentOrElse(
          i -> finalVo.setUrgent(i.getItemValue()),
          () ->
            ir.addError(
              "urgent",
              String.format(
                "必须为 %s 中之一",
                urgentItems
                  .stream()
                  .map(SysDictAllItem::getItemText)
                  .collect(Collectors.joining(", "))
              )
            )
        );
    }
    vo.setNotificationOfReceiptQuantity(
      SheetUtils.tryToInteger(row.getNotificationOfReceiptQuantity())
    );
    vo.setReceiptAboutQuantity(
      SheetUtils.tryToInteger(row.getReceiptAboutQuantity())
    );
    // 处理关联字段“关联单据号”
    if (
      !SheetUtils.isBlank(row.getDocRelatePurchaseOrderCode()) &&
      SheetUtils.isBlank(row.getDocRelate())
    ) {
      PurchaseOrderSearchParamPo docRelateSearchParam =
        new PurchaseOrderSearchParamPo();
      docRelateSearchParam.setLimit(2); // 最大只返回二行记录
      docRelateSearchParam.setPurchaseOrderCodeEq(
        SheetUtils.trim(row.getDocRelatePurchaseOrderCode())
      );
      docRelateSearchParam.applySqlSegments();
      List<PurchaseOrderItemVo> docRelateMatches = purchaseOrderMapper.search(
        docRelateSearchParam
      );
      if (docRelateMatches.size() == 0) {
        ir.addError(
          "docRelatePurchaseOrderCode",
          "未能在采购订单中找到匹配的数据"
        );
      } else if (docRelateMatches.size() > 1) {
        ir.addError(
          "docRelatePurchaseOrderCode",
          "关联不唯一，在采购订单中找到多个匹配的数据"
        );
      } else {
        vo.setDocRelate(docRelateMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", docRelateMatches.get(0).getId())
          .put("fromObjectName", "Receipt")
          .put("fromObjectId", vo.getId())
          .put("fromField", "docRelate")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(3);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains("buyer")
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("optUid")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("buyer")
              .rowFieldName("buyerName")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "receiptList"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName(null)
              .sourceType("api")
              .sourceApi(
                "/receipt/querySubtableData?purchaseOrderId=${context.docRelate}"
              )
              .targetFieldName("receiptList")
              .rowFieldName(null)
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "businessOrderSn"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("purchaseOrderCode")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("businessOrderSn")
              .rowFieldName("businessOrderSn")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(docRelateMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“仓库”
    if (
      !SheetUtils.isBlank(row.getWarehouseName()) &&
      SheetUtils.isBlank(row.getWarehouse())
    ) {
      WarehouseSearchParamPo warehouseSearchParam =
        new WarehouseSearchParamPo();
      warehouseSearchParam.setLimit(2); // 最大只返回二行记录
      warehouseSearchParam.setNameEq(SheetUtils.trim(row.getWarehouseName()));
      warehouseSearchParam.setFinalFilters(new ArrayList<>());
      warehouseSearchParam
        .getFinalFilters()
        .add(
          new PageSearchFilter()
            .setDataIndex(new DataIndex("widType"))
            .setOp("eq")
            .setValue("1")
        );
      warehouseSearchParam.applySqlSegments();
      List<WarehouseItemVo> warehouseMatches = warehouseMapper.search(
        warehouseSearchParam
      );
      if (warehouseMatches.size() == 0) {
        ir.addError("warehouseName", "未能在仓库即时库存中找到匹配的数据");
      } else if (warehouseMatches.size() > 1) {
        ir.addError(
          "warehouseName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setWarehouse(warehouseMatches.get(0).getId());
      }
    }
    // 处理关联字段“供应商”
    if (
      !SheetUtils.isBlank(row.getSupplierSupplierName()) &&
      SheetUtils.isBlank(row.getSupplier())
    ) {
      SupplierSearchParamPo supplierSearchParam = new SupplierSearchParamPo();
      supplierSearchParam.setLimit(2); // 最大只返回二行记录
      supplierSearchParam.setSupplierNameEq(
        SheetUtils.trim(row.getSupplierSupplierName())
      );
      supplierSearchParam.applySqlSegments();
      List<SupplierItemVo> supplierMatches = supplierMapper.search(
        supplierSearchParam
      );
      if (supplierMatches.size() == 0) {
        ir.addError("supplierSupplierName", "未能在供应商中找到匹配的数据");
      } else if (supplierMatches.size() > 1) {
        ir.addError(
          "supplierSupplierName",
          "关联不唯一，在供应商中找到多个匹配的数据"
        );
      } else {
        vo.setSupplier(supplierMatches.get(0).getId());
      }
    }
    // 处理关联字段“物流商”
    if (
      !SheetUtils.isBlank(row.getShipmentEnterpriseName()) &&
      SheetUtils.isBlank(row.getShipmentEnterprise())
    ) {
      LogisticsProviderSearchParamPo shipmentEnterpriseSearchParam =
        new LogisticsProviderSearchParamPo();
      shipmentEnterpriseSearchParam.setLimit(2); // 最大只返回二行记录
      shipmentEnterpriseSearchParam.setNameEq(
        SheetUtils.trim(row.getShipmentEnterpriseName())
      );
      shipmentEnterpriseSearchParam.applySqlSegments();
      List<LogisticsProviderItemVo> shipmentEnterpriseMatches =
        logisticsProviderMapper.search(shipmentEnterpriseSearchParam);
      if (shipmentEnterpriseMatches.size() == 0) {
        ir.addError("shipmentEnterpriseName", "未能在物流商中找到匹配的数据");
      } else if (shipmentEnterpriseMatches.size() > 1) {
        ir.addError(
          "shipmentEnterpriseName",
          "关联不唯一，在物流商中找到多个匹配的数据"
        );
      } else {
        vo.setShipmentEnterprise(shipmentEnterpriseMatches.get(0).getId());
        //20230706 调整
        final Map apiParams = MapUtil
          .builder()
          .put("id", shipmentEnterpriseMatches.get(0).getId())
          .put("fromObjectName", "Receipt")
          .put("fromObjectId", vo.getId())
          .put("fromField", "shipmentEnterprise")
          .build();

        final List<JoinModel> joinModels = new ArrayList<>(1);
        if (
          variables.get("IMPORT_FIELDS") == null ||
          !((Set<String>) variables.get("IMPORT_FIELDS")).contains(
              "logisticsCode"
            )
        ) {
          joinModels.add(
            JoinModel
              .builder()
              .sourceFieldName("id")
              .sourceType("field")
              .sourceApi(null)
              .targetFieldName("logisticsCode")
              .rowFieldName("logisticsCode")
              .apiParams(apiParams)
              .required(false)
              .importIgnore(false)
              .build()
          );
        }
        SheetUtils.joinHandle(
          null,
          ir,
          null,
          vo,
          CollUtil.getFirst(shipmentEnterpriseMatches),
          joinModels
        );
      }
    }
    // 处理关联字段“采购员”
    if (vo.getBuyer() != null) {
      row.setBuyerName(sysUserMapper.getNameById(vo.getBuyer()));
    } else if (
      !SheetUtils.isBlank(row.getBuyerName()) &&
      SheetUtils.isBlank(row.getBuyer())
    ) {
      SysUserSearch buyerSearchParam = new SysUserSearch();
      buyerSearchParam.setLimit(2); // 最大只返回二行记录
      buyerSearchParam.setNameEq(SheetUtils.trim(row.getBuyerName()));
      buyerSearchParam.applySqlSegments();
      List<SysUserItemVo> buyerMatches = sysUserMapper.search(buyerSearchParam);
      if (buyerMatches.size() == 0) {
        ir.addError("buyerName", "未能在用户中找到匹配的数据");
      } else if (buyerMatches.size() > 1) {
        ir.addError("buyerName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setBuyer(buyerMatches.get(0).getId());
      }
    }
    // 处理关联字段“自定义创建人”
    if (
      !SheetUtils.isBlank(row.getCreatorName()) &&
      SheetUtils.isBlank(row.getCreator())
    ) {
      SysUserSearch creatorSearchParam = new SysUserSearch();
      creatorSearchParam.setLimit(2); // 最大只返回二行记录
      creatorSearchParam.setNameEq(SheetUtils.trim(row.getCreatorName()));
      creatorSearchParam.applySqlSegments();
      List<SysUserItemVo> creatorMatches = sysUserMapper.search(
        creatorSearchParam
      );
      if (creatorMatches.size() == 0) {
        ir.addError("creatorName", "未能在用户中找到匹配的数据");
      } else if (creatorMatches.size() > 1) {
        ir.addError("creatorName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setCreator(creatorMatches.get(0).getId());
      }
    }
    // 处理关联字段“收货人”
    if (
      !SheetUtils.isBlank(row.getConsigneeName()) &&
      SheetUtils.isBlank(row.getConsignee())
    ) {
      SysUserSearch consigneeSearchParam = new SysUserSearch();
      consigneeSearchParam.setLimit(2); // 最大只返回二行记录
      consigneeSearchParam.setNameEq(SheetUtils.trim(row.getConsigneeName()));
      consigneeSearchParam.applySqlSegments();
      List<SysUserItemVo> consigneeMatches = sysUserMapper.search(
        consigneeSearchParam
      );
      if (consigneeMatches.size() == 0) {
        ir.addError("consigneeName", "未能在用户中找到匹配的数据");
      } else if (consigneeMatches.size() > 1) {
        ir.addError("consigneeName", "关联不唯一，在用户中找到多个匹配的数据");
      } else {
        vo.setConsignee(consigneeMatches.get(0).getId());
      }
    }
    // 处理关联字段“收货仓库”
    if (
      !SheetUtils.isBlank(row.getClerkName()) &&
      SheetUtils.isBlank(row.getClerk())
    ) {
      WarehouseSearchParamPo clerkSearchParam = new WarehouseSearchParamPo();
      clerkSearchParam.setLimit(2); // 最大只返回二行记录
      clerkSearchParam.setNameEq(SheetUtils.trim(row.getClerkName()));
      clerkSearchParam.applySqlSegments();
      List<WarehouseItemVo> clerkMatches = warehouseMapper.search(
        clerkSearchParam
      );
      if (clerkMatches.size() == 0) {
        ir.addError("clerkName", "未能在仓库即时库存中找到匹配的数据");
      } else if (clerkMatches.size() > 1) {
        ir.addError(
          "clerkName",
          "关联不唯一，在仓库即时库存中找到多个匹配的数据"
        );
      } else {
        vo.setClerk(clerkMatches.get(0).getId());
      }
    }

    return ir;
  }

  /**
   * 导入预览
   * @param sysFile 已上传到系统的文件
   * @param templateId 要使用的模版编号
   * @param allowOverrides 允许覆盖
   */
  @Override
  public List<ImportRow<ReceiptImportPo>> importPreview(
    SysFile sysFile,
    Long templateId,
    boolean allowOverrides
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    try (InputStream in = fileService.read(sysFile)) {
      List<ImportRow<ReceiptImportPo>> rows = new ArrayList<>();

      // 读取 Excel 到 rows
      EasyExcel
        .read(in)
        .useDefaultListener(false)
        .registerReadListener(
          new TemplateModelBuildEventListener<>(
            ReceiptImportPo.class,
            importTemplate
          ) {
            @Override
            public void invokeRow(ReceiptImportPo row, AnalysisContext cxt) {
              ReceiptVo vo = new ReceiptVo();
              ImportRow<ReceiptImportPo> ir = excelToImportRow(
                row,
                cxt.readRowHolder().getRowIndex(),
                vo,
                variables,
                allowOverrides
              );
              if (ir.isEmptyRow()) {
                return;
              }
              if (allowOverrides) {
                // FIXME: 未在平台上配置此对象《作为导入唯一识别》的《逻辑分组》配置，无法处理更新模式
              }
              rows.add(ir);
            }
          }
        )
        .sheet()
        .doRead();

      return rows;
    }
  }

  /**
   * 完成导入
   * @param rows 预导入的行信息
   */
  @DataActivity(action = SysDataActivityAction.Import)
  @Transactional(rollbackFor = Exception.class)
  @Override
  public void importDone(
    List<ImportRow<ReceiptImportPo>> rows,
    Long templateId
  ) throws Exception {
    SysImportTemplate importTemplate = null;
    if (templateId != null && templateId > 0) {
      importTemplate = importTemplateService.getById(templateId);
      if (importTemplate == null) {
        throw new RException("指定的模版不可用！");
      }
    }
    String sysImportBatchNo = StrUtil.concat(
      true,
      DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN),
      IdUtil.nanoId(4)
    );
    List<Long> importedIdList = new ArrayList<>();
    SysDataActivityAopHelper.clear();
    final SysDataActivityAopHelper.DataActivityAopContext context =
      SysDataActivityAopHelper.getOrCreateContext();
    Map<String, Object> variables = new HashMap<>();

    // 标记由模版直接导入的字段集
    if (importTemplate != null) {
      variables.put(
        "IMPORT_FIELDS",
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .map(SysImportTemplate.Mapping::getField)
          .collect(Collectors.toSet())
      );
    }
    for (int i = 0; i < rows.size(); i++) {
      ImportRow<ReceiptImportPo> row = rows.get(i);
      Long updateId = row.getUpdateId();
      ReceiptVo vo = new ReceiptVo();
      row =
        excelToImportRow(row.getRow(), row.getRowNumber(), vo, variables, true);
      if (row.getErrors() != null && row.getErrors().size() > 0) {
        throw new RException(
          String.format(
            "第%d行（Excel第%d行）数据验证错误：%s",
            i + 1,
            row.getRowNumber(),
            row.getJoinErrorMessage()
          )
        );
      }
      if (updateId != null) {
        vo.setId(updateId);
      }
      // 重建"收货单号"
      if (
        importTemplate != null &&
        importTemplate
          .getSetting()
          .getMappings()
          .stream()
          .anyMatch(m ->
            Boolean.TRUE.equals(m.getNeedRecreate()) &&
            "orderSn".equals(m.getField())
          )
      ) {
        vo.setOrderSn(
          sysSerialService.getNewSerial(
            new NewSerialRequest(null, "Receipt.orderSn")
          )
        );
      }

      SheetUtils.setSysImportTemplateName(
        vo,
        null == importTemplate ? "默认模板" : importTemplate.getTitle()
      );
      SheetUtils.setSysImportBatchNo(vo, sysImportBatchNo);
      if (updateId == null) {
        importedIdList.add(create(vo));
      } else {
        self.update(vo);
        importedIdList.add(vo.getId());
      }
    }
    context.getIdList().addAll(importedIdList);
  }

  /**
   * 导出
   * @param templateId 使用模版（可以是 null 或 0 表示系统默认导出模版）
   * @param search 查询条件
   */
  @DataActivity(action = SysDataActivityAction.Export)
  @Override
  public void export(
    Long templateId,
    ReceiptSearchParamPo search,
    HttpServletResponse response
  ) throws Exception {
    if (templateId != null && templateId > 0) {
      SysImportTemplate sysImportTemplate = importTemplateService.getById(
        templateId
      );
      if (sysImportTemplate == null) {
        throw new RException("所选的导出模版不可用");
      }
      CustomExcelExport.CustomExcelExportOptions exportOptions =
        new CustomExcelExport.CustomExcelExportOptions();
      exportOptions.setImportTemplate(sysImportTemplate);
      exportOptions.setSearchParam(search);
      exportOptions.setMainService(this);
      exportOptions.addFieldMappingOption(
        "receiptType",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> ReceiptReceiptTypeEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "docRelate",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getDocRelatePurchaseOrderCode())
          )
      );
      exportOptions.addFieldMappingOption(
        "warehouse",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getWarehouseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "supplier",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getSupplierSupplierName())
          )
      );
      exportOptions.addFieldMappingOption(
        "shipmentEnterprise",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getShipmentEnterpriseName())
          )
      );
      exportOptions.addFieldMappingOption(
        "buyer",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getBuyerName())
          )
      );
      exportOptions.addFieldMappingOption(
        "consignee",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) ->
            String.valueOf(((ReceiptItemVo) r).getConsigneeName())
          )
      );
      exportOptions.addFieldMappingOption(
        "status",
        new CustomExcelExport.FieldMappingOption()
          .setConverter((o, r) -> ReceiptStatusEnums.toLabel((String) o))
      );
      exportOptions.addFieldMappingOption(
        "urgent",
        new CustomExcelExport.FieldMappingOption().setDictCode("SCM00008")
      );
      exportOptions.addStringFields(
        "orderSn",
        "receiptType",
        "docRelatePurchaseOrderCode",
        "warehouseName",
        "supplierSupplierName",
        "shipmentEnterpriseName",
        "logisticsCode",
        "buyerName",
        "consigneeName",
        "remarks",
        "status",
        "urgent"
      );

      String fileName = String.format(
        "收货单(%s).xlsx",
        DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
      );
      ResponseUtils.setAttachmentFileName(response, fileName);
      customExcelExport.run(exportOptions, response.getOutputStream());
      return;
    }
    List<SysDictAllItem> urgentItems = sysDictService.getDictItems("SCM00008");
    search.setPageSize(EXPORT_QUERY_MAX_SIZE);
    int current = 1;
    List<ReceiptExcelPo> items = new ArrayList<ReceiptExcelPo>();
    while (true) {
      search.setCurrent(current);
      search.setSelectFields(Collections.singletonList("@export"));
      Page<ReceiptItemVo> page = this.pageSearch(search);
      if (page.getTotal() > EXPORT_MAX_SIZE) {
        throw new RException("导出记录数超出限制！");
      }
      List<ReceiptItemVo> list = page.getRecords();
      if (list.isEmpty()) {
        break;
      }
      for (ReceiptItemVo item : list) {
        ReceiptExcelPo excel = new ReceiptExcelPo();
        BeanUtils.copyProperties(item, excel);
        excel.setReceiptType(
          ReceiptReceiptTypeEnums.toLabel(item.getReceiptType())
        );
        excel.setStatus(ReceiptStatusEnums.toLabel(item.getStatus()));
        if (item.getUrgent() != null) {
          urgentItems
            .stream()
            .filter(i -> i.getItemValue().equals(item.getUrgent()))
            .findFirst()
            .ifPresent(i -> excel.setUrgent(i.getItemText()));
        }

        items.add(excel);
      }
      if (list.size() < EXPORT_QUERY_MAX_SIZE) {
        break;
      }
      current++;
    }

    String fileName = String.format(
      "收货单(%s).xlsx",
      DateUtils.toString(null, DateUtils.PATTERN_DATE_TIME)
    );
    ResponseUtils.setAttachmentFileName(response, fileName);
    EasyExcel
      .write(response.getOutputStream())
      .registerWriteHandler(new CustomExcelHandler())
      .sheet()
      .head(ReceiptExcelPo.class)
      .doWrite(items);
  }

  /**
   * 通过收货单号查询收货单主键(重复时返回最新的主键)
   */
  @Override
  public Long getIdByOrderSn(String orderSn) {
    return this.baseMapper.getIdByOrderSn(orderSn);
  }

  /**
   * 通过收货单号查询收货单多主键(重复时返回最新的主键)
   */
  @Override
  public List<Long> getIdsByOrderSn(List<String> list) {
    return this.baseMapper.getIdsByOrderSn(list);
  }

  /**
   * 通过收货单主键查询收货单号
   */
  @Override
  public String getOrderSnById(Long id) {
    return this.baseMapper.getOrderSnById(id);
  }

  /**
   * 通过收货单主键查询收货单号列表
   */
  @Override
  public List<String> getOrderSnByIds(List<Long> ids) {
    List<Map<String, Object>> maps = this.baseMapper.getOrderSnByIds(ids);
    // 将返回重新排列为输入相同顺序
    return ids
      .stream()
      .map(id -> {
        Optional<Map<String, Object>> optionalMap = maps
          .stream()
          .filter(map -> id.equals(map.get("id")))
          .findFirst();
        return optionalMap
          .map(stringObjectMap -> (String) stringObjectMap.get("orderSn"))
          .orElse(null);
      })
      .collect(Collectors.toList());
  }

  /**
   * 获取详情
   * @param id 收货单的主键
   */
  @DataActivity(action = SysDataActivityAction.View)
  @Override
  public ReceiptVo getVoById(Long id) throws Exception {
    ReceiptVo vo = this.baseMapper.selectVoById(id);
    if (vo == null) {
      return null;
    }

    ReceiptProductSearchParamPo receiptListSearchParamPo =
      new ReceiptProductSearchParamPo();
    receiptListSearchParamPo.setParentReceipt(id);
    // 禁用通用数据权限过滤
    receiptListSearchParamPo.setDisableDataPremissions(true);
    receiptListSearchParamPo.getExtendData().put("queryMode", "sub");
    receiptListSearchParamPo.getExtendData().put("queryParent", "Receipt");
    receiptListSearchParamPo.applySqlSegments();
    vo.setReceiptList(receiptProductService.search(receiptListSearchParamPo));

    return vo;
  }

  /**
   * 分页查询收货单
   * @param search 查询条件
   * @return 收货单分页查询结果
   */
  @Override
  public Page<ReceiptItemVo> pageSearch(ReceiptSearchParamPo search) {
    Page<ReceiptItemVo> page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("receipt_date DESC", "t.", SORT_FIELD_MAP);
    page = this.baseMapper.pageSearch(search.toPage(), search);
    List<Long> recordIds = page
      .getRecords()
      .stream()
      .map(ReceiptItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });
    return page;
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   */
  protected Page<?> appendWithChild(Page<ReceiptItemVo> pageResult) {
    return appendWithChild(pageResult, null);
  }

  /**
   * 通用方法，为列表添加子表数据
   * @param pageResult 列表结果
   * @param sort 子表排序
   */
  protected Page<?> appendWithChild(
    Page<ReceiptItemVo> pageResult,
    String sort
  ) {
    if (
      pageResult == null ||
      pageResult.getRecords() == null ||
      pageResult.getRecords().isEmpty()
    ) {
      return pageResult;
    }
    Page<JSONObject> withChildPage = new Page<>(
      pageResult.getCurrent(),
      pageResult.getSize(),
      pageResult.getTotal()
    );
    withChildPage.setRecords(new ArrayList<>());

    ReceiptProductSearchParamPo receiptListSearchParamPo =
      new ReceiptProductSearchParamPo();
    receiptListSearchParamPo.setSort(sort);
    receiptListSearchParamPo.setPageSize(200);
    receiptListSearchParamPo.setParentReceiptInList(
      pageResult
        .getRecords()
        .stream()
        .map(ReceiptItemVo::getId)
        .collect(Collectors.toList())
    );
    // 禁用通用数据权限过滤
    receiptListSearchParamPo.setDisableDataPremissions(true);

    Map<String, Page<ReceiptProductItemVoPages>> receiptListMaps =
      receiptProductService.pagesByParentReceipt(receiptListSearchParamPo);

    for (ReceiptItemVo itemVo : pageResult.getRecords()) {
      JSONObject itemJson = (JSONObject) JSONObject.toJSON(itemVo);
      itemJson.put(
        "receiptList",
        receiptListMaps.get(itemVo.getId().toString())
      );
      withChildPage.getRecords().add(itemJson);
    }
    return withChildPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 收货单分页查询结果
   */
  @Override
  public Page<?> pageWithChildSearch(ReceiptSearchParamPo search) {
    return appendWithChild(
      pageSearch(search),
      search.toChildSort("receiptList")
    );
  }

  /**
   * 仅获取子表的查询结果
   * @param parentId 主表编号
   * @param search 查询条件(仅使用分页参数，不处理其它条件)
   * @return
   */
  @Override
  public Page<?> pageOnlyChildSearch(
    Long parentId,
    ReceiptSearchParamPo search
  ) {
    ReceiptSearchParamPo parentSearchParam = new ReceiptSearchParamPo();
    parentSearchParam.setIdEq(parentId);
    List<ReceiptItemVo> parentList = search(parentSearchParam);
    if (parentList.size() > 0) {
      ReceiptItemVo itemVo = parentList.get(0);

      ReceiptProductSearchParamPo receiptListSearchParamPo =
        new ReceiptProductSearchParamPo();
      receiptListSearchParamPo.setPageSize(search.getPageSize());
      receiptListSearchParamPo.setCurrent(search.getCurrent());
      receiptListSearchParamPo.setParentReceipt(itemVo.getId());
      // 禁用通用数据权限过滤
      receiptListSearchParamPo.setDisableDataPremissions(true);
      return receiptProductService.pageSearch(receiptListSearchParamPo);
    } else {
      return null;
    }
  }

  /**
   * 收货单快速查询选项(有缓存)
   * @param search 查询条件
   * @return 选项结果
   */
  @Override
  @Cacheable(
    value = CacheConfig.FAST,
    key = "'ReceiptOptions::' + @userInfo.userTypeAndId + '::' + #search.keyword"
  )
  public List<OptionItem<ReceiptItemVo>> searchOptions(
    ReceiptSearchParamPo search
  ) {
    search.initSort("receipt_date DESC", "t.", SORT_FIELD_MAP);
    return this.baseMapper.searchOptions(search);
  }

  /**
   * 列表查询收货单
   * @param search 查询条件
   * @return 收货单列表查询结果
   */
  @Override
  public List<ReceiptItemVo> search(ReceiptSearchParamPo search) {
    search.initSort("receipt_date DESC", "t.", SORT_FIELD_MAP);
    return this.baseMapper.search(search);
  }

  /**
   * 查询收货单最后更新时间
   * @param search 查询条件
   * @return 收货单最后更新时间
   */
  @Override
  public Date searchLastUpdateTime(ReceiptSearchParamPo search) {
    return this.baseMapper.searchLastUpdateTime(search);
  }

  /**
   * 打印产品条码（自定义）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印产品条码（自定义）操作"
  )
  @Override
  public void printProductBarCodesCustom(Long id) throws Exception {
    if (receiptPrintProductBarCodesCustomAction == null) {
      throw new Exception("此操作当前不可用");
    }
    receiptPrintProductBarCodesCustomAction.run(id);
  }

  /**
   * 打印产品条码（模版）
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了打印产品条码（模版）操作"
  )
  @Override
  public void printProductBarCodesTemplate(Long id) throws Exception {
    if (receiptPrintProductBarCodesTemplateAction == null) {
      throw new Exception("此操作当前不可用");
    }
    receiptPrintProductBarCodesTemplateAction.run(id);
  }

  /**
   * 导入收货
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了导入收货操作"
  )
  @Override
  public void importAndReceive(List<Long> ids) throws Exception {
    if (receiptImportAndReceiveAction == null) {
      throw new Exception("此操作当前不可用");
    }
    receiptImportAndReceiveAction.run(ids);
  }

  /**
   * 导入快捷入库
   */
  @DataActivity(
    action = SysDataActivityAction.Other,
    message = "%s执行了导入快捷入库操作"
  )
  @Override
  public void importShortcutToLibrary(List<Long> ids) throws Exception {
    if (receiptImportShortcutToLibraryAction == null) {
      throw new Exception("此操作当前不可用");
    }
    receiptImportShortcutToLibraryAction.run(ids);
  }

  /**
   * 视图选项卡标题上显示计数
   */

  @Override
  public Map getTabHeaderShowTotal() {
    ReceiptSearchParamPo search = new ReceiptSearchParamPo();
    return MapUtil
      .builder()
      .put("All1", this.baseMapper.all1Count(search))
      .put("WaitForReceiving", this.baseMapper.waitForReceivingCount(search))
      .put("Done", this.baseMapper.doneCount(search))
      .build();
  }

  /**
   * 全部
   */
  @Override
  public List<ReceiptItemVo> all1(ReceiptSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.all1(search);
  }

  /**
   * 全部分页
   */
  @Override
  public Page<ReceiptItemVo> all1Page(ReceiptSearchParamPo search) {
    Page<ReceiptItemVo> all1Page = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return all1Page;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return all1Page;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    all1Page =
      this.baseMapper.all1Page(
          search.toPage(this.baseMapper.all1Count(search)),
          search
        );
    List<Long> recordIds = all1Page
      .getRecords()
      .stream()
      .map(ReceiptItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return all1Page;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return all1Page;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    all1Page
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return all1Page;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 收货单分页查询结果
   */
  @Override
  public Page<?> all1PageWithChildSearch(ReceiptSearchParamPo search) {
    return appendWithChild(all1Page(search), search.toChildSort("receiptList"));
  }

  /**
   * 查询全部最后更新时间
   * @param search 查询条件
   * @return 全部最后更新时间
   */
  @Override
  public Date all1LastUpdateTime(ReceiptSearchParamPo search) {
    return this.baseMapper.all1LastUpdateTime(search);
  }

  /**
   * 待收货
   */
  @Override
  public List<ReceiptItemVo> waitForReceiving(ReceiptSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.waitForReceiving(search);
  }

  /**
   * 待收货分页
   */
  @Override
  public Page<ReceiptItemVo> waitForReceivingPage(ReceiptSearchParamPo search) {
    Page<ReceiptItemVo> waitForReceivingPage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return waitForReceivingPage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return waitForReceivingPage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    waitForReceivingPage =
      this.baseMapper.waitForReceivingPage(
          search.toPage(this.baseMapper.waitForReceivingCount(search)),
          search
        );
    List<Long> recordIds = waitForReceivingPage
      .getRecords()
      .stream()
      .map(ReceiptItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return waitForReceivingPage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return waitForReceivingPage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    waitForReceivingPage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return waitForReceivingPage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 收货单分页查询结果
   */
  @Override
  public Page<?> waitForReceivingPageWithChildSearch(
    ReceiptSearchParamPo search
  ) {
    return appendWithChild(
      waitForReceivingPage(search),
      search.toChildSort("receiptList")
    );
  }

  /**
   * 查询待收货最后更新时间
   * @param search 查询条件
   * @return 待收货最后更新时间
   */
  @Override
  public Date waitForReceivingLastUpdateTime(ReceiptSearchParamPo search) {
    return this.baseMapper.waitForReceivingLastUpdateTime(search);
  }

  /**
   * 已完成
   */
  @Override
  public List<ReceiptItemVo> done(ReceiptSearchParamPo search) {
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    return this.baseMapper.done(search);
  }

  /**
   * 已完成分页
   */
  @Override
  public Page<ReceiptItemVo> donePage(ReceiptSearchParamPo search) {
    Page<ReceiptItemVo> donePage = new Page<>();
    if (
      Objects.nonNull(search.getWfStatus()) &&
      StringUtils.hasText(search.getFormName())
    ) {
      List<WorkFlow> workFlowList = workFlowService.queryWfListByStatus(
        search.getWfStatus(),
        search.getFormName()
      );
      if (CollectionUtils.isEmpty(workFlowList)) {
        return donePage;
      }
      List<Long> ids = workFlowList
        .stream()
        .map(WorkFlow::getRecordId)
        .collect(Collectors.toList());
      if (CollectionUtils.isEmpty(ids)) {
        return donePage;
      }
      search.setSelectedIds(ids);
    }
    search.initSort("t.id desc", "t.", SORT_FIELD_MAP);
    donePage =
      this.baseMapper.donePage(
          search.toPage(this.baseMapper.doneCount(search)),
          search
        );
    List<Long> recordIds = donePage
      .getRecords()
      .stream()
      .map(ReceiptItemVo::getId)
      .collect(Collectors.toList());
    if (CollectionUtils.isEmpty(recordIds)) {
      return donePage;
    }
    List<WorkFlow> workFlows = workFlowService.queryWfList(
      recordIds,
      Collections.singletonList(search.getFormName())
    );
    if (CollectionUtils.isEmpty(workFlows)) {
      return donePage;
    }
    Map<Long, Integer> flowMap = workFlows
      .stream()
      .collect(Collectors.toMap(WorkFlow::getRecordId, WorkFlow::getWfStatus));
    donePage
      .getRecords()
      .stream()
      .forEach(item -> {
        if (!flowMap.containsKey(item.getId())) {
          return;
        }
        item.setWfStatus(flowMap.get(item.getId()));
      });

    return donePage;
  }

  /**
   * 获取包括子表的查询结果
   * @param search 查询条件
   * @return 收货单分页查询结果
   */
  @Override
  public Page<?> donePageWithChildSearch(ReceiptSearchParamPo search) {
    return appendWithChild(donePage(search), search.toChildSort("receiptList"));
  }

  /**
   * 查询已完成最后更新时间
   * @param search 查询条件
   * @return 已完成最后更新时间
   */
  @Override
  public Date doneLastUpdateTime(ReceiptSearchParamPo search) {
    return this.baseMapper.doneLastUpdateTime(search);
  }

  /**
   * 更新收货单的状态为1
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object updateReceiptStatusToFinished(JSONObject args)
    throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_UpdateReceiptStatusToFinished.js",
      args,
      this
    );
  }

  /**
   * 质检按钮更新数据
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object checkButtonUpdatesData(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_CheckButtonUpdatesData.js",
      args,
      this
    );
  }

  /**
   * 收货单收货按钮
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object receiptReceiptButton(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_ReceiptReceiptButton.js",
      args,
      this
    );
  }

  /**
   * 快捷入库
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object quickStorage(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_QuickStorage.js",
      args,
      this
    );
  }

  /**
   * 查询子表
   */
  @Override
  public List<ReceiptQuerySubtableResult> querySubtable(
    ReceiptQuerySubtableParam param
  ) {
    return this.baseMapper.querySubtable(param);
  }

  /**
   * 关联单据（入库单）
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object relatedDocuments(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_RelatedDocuments.js",
      args,
      this
    );
  }

  /**
   * 查询子表数据
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object querySubtableData(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_QuerySubtableData.js",
      args,
      this
    );
  }

  /**
   * 关联单据（质检单）
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object relatedDocumentsQqualityInspectionForm(JSONObject args)
    throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_RelatedDocumentsQqualityInspectionForm.js",
      args,
      this
    );
  }

  /**
   * 免检
   * @param args 参数
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Object exemptedInspection(JSONObject args) throws Exception {
    executeScriptEngine.requestParamUnion(args);
    return executeScriptEngine.callJsInResource(
      "scripts/Receipt_ExemptedInspection.js",
      args,
      this
    );
  }
}
